<template>
    <div>
        <div class="custom-audio-player">
            <!-- 隐藏原生控件 -->
            <!-- <audio ref="audioRef" :src="audioUrl" @timeupdate="handleTimeUpdate"
                @loadedmetadata="handleLoadedMetadata" @ended="handleAudioEnd"></audio> -->
            <audio ref="audioRef" :src="audioUrl" @timeupdate="handleTimeUpdate" @loadedmetadata="handleLoadedMetadata"
                @ended="handleAudioEnd"></audio>

            <!-- 自定义控制界面 -->
            <div class="controls">
                <!-- 播放/暂停控制 -->
                <span @click="togglePlay"> <a-icon v-if="isPlaying" type="pause"
                        style="color:#316adc; cursor: pointer;font-size: 16px;" /> <a-icon v-else type="caret-right"
                        style="color:#316adc; cursor: pointer; font-size: 16px;" /> </span>
                <!-- 时间显示 -->
                <span class="time">
                    {{ formatTime(currentTime) }}/{{ formatTime(duration) }}
                </span>
                <!-- 进度条 -->
                <input type="range" v-model="progress" min="0" :max="duration" @input="seek" class="progress-bar"
                    :style="{ '--progress': progress / duration }">
                <a-select class="select-seed" v-model="playbackRate" @change="changeSpeed"
                    style="width: 48px; height: 20px;color: #64a5ff;" dropdownClassName="dropdownClassNameSpeed">
                    <a-select-option value="1x">1x</a-select-option>
                    <a-select-option value="2x">2x</a-select-option>
                    <a-select-option value="3x">3x</a-select-option>
                    <a-select-option value="4x">4x</a-select-option>
                </a-select>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'recordingItem',
    props: {
        audioUrl: {
            type: String,
        },
    },
    data() {
        return {
            visible: false,
            isPlaying: false,
            currentTime: 0,
            duration: 0,
            progress: 0,
            playbackRate: '1x',
            audioElement: null
            // audioUrl: 'http://122.13.6.239:8881/copzhvir/4001012265/20250503/18607698589-18507693527-B-2505032356001961000108480027a449.wav'
        }
    },
    watch: {
        // 当外部传入的 audioUrl 变化时重新加载
        audioUrl: {
            immediate: true,
            handler(newVal) {
                if (!newVal) return
                this.reset()
                this.$nextTick(() => {
                    this.loadAudio(newVal)
                })
            }
        }
    },
    mounted() {
        // if(this.audioUrl) {
        //     this.initAudio();
        // } else {
        //     console.error("音频URL未提供");
        // }
    },
    beforeDestroy() {
        this.stopAudioPlayback();

        // 移除可能的事件监听器
        if (this.audioElement) {
            this.audioElement.removeEventListener('ended', this.handleAudioEnd);
            this.audioElement.removeEventListener('timeupdate', this.handleTimeUpdate);
            this.audioElement.removeEventListener('loadedmetadata', this.handleLoadedMetadata);
        }
    },
    methods: {
        /* 1. 加载音频 */
        loadAudio(src) {
            const audio = this.$refs.audioRef
            if (!audio) return
            // 关键：先清缓存
            audio.removeAttribute('src')
            audio.load()
            // 再赋新地址
            audio.src = src
            audio.load() // 强制重新解析
            console.log('[loadAudio] 设置 src:', src)
            // 预加载头 1 byte，强制浏览器解析元数据
            fetch(src, { method: 'HEAD' })   // 或 fetch(src, { headers:{ Range:'bytes=0-1023' } })
                .then(() => {
                    audio.src = src
                    audio.load()
                    console.log('[loadAudio] 设置 src:222=', src)
                })

        },
        /* 8. 重置 */
        reset() {
            const audio = this.$refs.audioRef
            if (!audio) return
            audio.pause()
            audio.removeAttribute('src')
            audio.load()
            this.duration = 0
            this.currentTime = 0
            this.isPlaying = false
            this.progress = 0
            this.playbackRate = '1x'
        },

        togglePlay() {
            if (!this.$refs.audioRef) return;

            if (this.$refs.audioRef.paused) {
                this.$refs.audioRef.play();
                this.isPlaying = true;
            } else {
                this.$refs.audioRef.pause();
                this.isPlaying = false;
            }
        },
        // 时间更新处理
        handleTimeUpdate() {
            this.currentTime = this.$refs.audioRef.currentTime;
            this.progress = this.$refs.audioRef.currentTime;
        },

        // 加载元数据
        handleLoadedMetadata() {
            const audio = this.$refs.audioRef
            const d = audio.duration
            console.log('[onLoaded] duration:', d)
            this.duration = isFinite(d) ? d : 0
            // this.duration = this.$refs.audioRef.duration;
            // console.log("🚀 ~ handleLoadedMetadata ~ his.duration:", this.duration)
        },

        // 调整播放进度
        seek(e) {
            if (!this.$refs.audioRef) return;
            this.$refs.audioRef.currentTime = e.target.value;
        },

        // 修改播放速度
        changeSpeed(v) {
            console.log("🚀 ~ changeSpeed ~ v:", v)
            if (this.$refs.audioRef) {
                let rateNum = Number(v.slice(0, v.length - 1))
                this.$refs.audioRef.playbackRate = rateNum;
            }
        },

        // 时间格式化
        formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
        },
        modalCancel() {
            this.visible = false
        },
        // 初始化音频
        initAudio() {
            this.audioElement = this.$refs.audioRef
            console.log("🚀 ~ initAudio ~ this.audioElement:", this.audioElement)
            // this.audioElement.addEventListener('timeupdate', this.updateProgress)
            this.audioElement.addEventListener('ended', this.handleAudioEnd)
            this.audioElement.addEventListener('loadedmetadata', this.handleLoadedMetadata)
        },
        handleAudioEnd() {
            this.isPlaying = false
            this.$refs.audioRef.currentTime = 0
            this.resetPlayerState()
        },
        // 停止播放并重置
        stopAudioPlayback() {
            if (this.audioElement) {
                this.audioElement.pause()
                this.audioElement.currentTime = 0
                this.isPlaying = false
            }
        },
        // 重置播放器状态
        resetPlayerState() {
            this.progress = 0
            this.playbackRate = '1x'
        },

    },
}
</script>
<style lang="less">
.dropdownClassNameSpeed {
    width: 40px !important;

    .ant-select-dropdown-menu-item {
        text-align: center;
        padding: 2px;
        color: #64a5ff;
    }
}
</style>
<style lang="less" scoped>
.custom-audio-player {
    width: 100%;
    // position: relative;
    // max-width: 600px;
    // margin: 20px auto;
    padding: 10px;
    background: #f5f5f5;
    border-radius: 8px;
}

.controls {
    display: flex;
    align-items: center;
    gap: 6px;
}

button {
    padding: 8px 16px;
    background: #2196F3;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

// .progress-bar {
//     flex-grow: 1;
//     height: 8px;
// }

.time {
    // font-family: monospace;
    // font-size: 0.9em;
    display: inline-block;
    color: #666;
    min-width: 90px;
}

.select-seed {
    /deep/ .ant-select-arrow {
        display: none;
    }

    /deep/ .ant-select-selection__rendered {
        line-height: 20px;
        margin: 0;
    }

    /deep/ .ant-select-selection--single {
        height: 22px;
    }

    /deep/ .ant-select-selection-selected-value {
        // margin: 0 2px;
        width: 100%;
        text-align: center;
    }
}

/* 整体进度条容器 */
.progress-bar {
    --track-height: 8px;
    --thumb-size: 8px;
    --filled-color: #88a9ea;
    /* 红色 */
    --unfilled-color: #dfe8f9;
    /* 未填充颜色 */
    width: 100%;
    height: var(--track-height);
    -webkit-appearance: none;
    background: transparent;
    border-radius: calc(var(--track-height) / 2)
}

/* Webkit 浏览器填充部分 */
.progress-bar::-webkit-slider-runnable-track {
    height: var(--track-height);
    border-radius: calc(var(--track-height) / 2);
    background: linear-gradient(to right,
            var(--filled-color) 0%,
            var(--filled-color) calc(var(--progress) * 100%),
            var(--unfilled-color) calc(var(--progress) * 100%),
            var(--unfilled-color) 100%);
}

/* Firefox 专用填充样式 */
.progress-bar::-moz-range-progress {
    background: var(--filled-color);
    height: var(--track-height);
    border-radius: 2px;
}

/* 滑块样式保持原有配置 */
.progress-bar::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 0;
    /* 隐藏滑块 */
    height: 0;
    /* 隐藏滑块 */
    opacity: 0;
    /* 双重保障 */
    pointer-events: none;
    /* 防止误操作 */
    //   -webkit-appearance: none;
    //   width: var(--thumb-size);
    //   height: var(--thumb-size);
    //   background: #88a9ea;
    //   border: 2px solid var(--filled-color);
    //   border-radius: 50%;
    //   margin-top: calc((var(--track-height) - var(--thumb-size)) / 2);
}

.progress-bar::-moz-range-thumb {
    width: 0;
    height: 0;
    opacity: 0;
    border: none;
    //   width: var(--thumb-size);
    //   height: var(--thumb-size);
    //   background: #88a9ea;
    //   border: 1px solid var(--filled-color);
    //   border-radius: 50%;
}

/* 兼容新版 Edge */
.progress-bar::-ms-thumb {
    width: 0;
    height: 0;
    opacity: 0;
}

/* 保持轨道可点击 */
.progress-bar::-webkit-slider-runnable-track {
    cursor: pointer;
}

.progress-bar::-moz-range-track {
    cursor: pointer;
}
</style>